<template>
  <el-container>
    <el-aside width="10%">

    </el-aside>
    <el-main>
      <el-row>
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span style="font-size: 25px;">文章管理</span>
              </div>
            </template>

<!--            <div class="data-empty">-->
<!--              <el-empty :image-size="200" />-->
<!--            </div>-->

            <div class="data-content">
              <el-table stripe :data="articlelist" :default-sort="{ prop: 'date', order: 'descending' }" max-height="900"
                        v-loading="loading"
                        element-loading-text="Loading..."
                        :element-loading-spinner="svg"
                        element-loading-svg-view-box="-10, -10, 50, 50">
                <el-table-column fixed prop="title" label="标题"/>
                <el-table-column label="分类">
                  <template #default="scope">
                    <el-tag v-if="scope.row.category === 1" type="primary" size="large">技术分享</el-tag>
                    <el-tag v-else-if="scope.row.category === 2" type="success" size="large">学习笔记</el-tag>
                    <el-tag v-else-if="scope.row.category === 3" type="warning" size="large">随心所写</el-tag>
                    <el-tag v-else-if="scope.row.category === 4" type="danger" size="large">剑指Offer</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createtime" sortable label="发布时间"/>
                <el-table-column label="状态">
                  <template #default="scope">
                    <el-tag v-if="scope.row.status === 0" type="primary" size="large">审核中</el-tag>
                    <el-tag v-else-if="scope.row.status === 1" type="success" size="large">审核通过</el-tag>
                    <el-tag v-else-if="scope.row.status === 2" type="danger" size="large">未通过</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="消息">
                  <template #default="scope">
                    <el-popover
                        placement="top-start"
                        title="Message"
                        :width="200"
                        trigger="hover"
                        :content="`${scope.row.message}`"
                    >
                      <template #reference>
                        <el-button type="warning">查看消息</el-button>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right">
                  <template #default="scope">
                    <div v-if="scope.row.status === 1">
                      <el-button type="danger" :icon="Delete" circle @click="deleteArticle(scope.$index,scope.row.id)" />
                    </div>
                    <div v-if="scope.row.status === 2">
                      <el-button type="primary" :icon="Edit" circle @click="getArticle(scope.row.id)"/>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <template #footer>
              <span>
                只能对审核过的文章进行修改和删除
              </span>
            </template>
          </el-card>
        </el-col>
      </el-row>
      <el-drawer direction="rtl" v-model="drawer" size="60%">
        <template #header>
          <h3>编辑</h3>
        </template>
        <template #default>
          <el-form ref="formRef" :model="article" :rules="rules" status-icon>
            <el-form-item  label="标题" prop="title">
              <el-input v-model="article.title"/>
            </el-form-item>
            <el-form-item label="概述" prop="abstracts">
              <el-input v-model="article.abstracts"/>
            </el-form-item>
            <el-form-item label="文章分类" prop="category">
              <el-select placeholder="请选择文章分类" v-model="article.category">
                <el-option label="技术分享" value="1"/>
                <el-option label="学习笔记" value="2"/>
                <el-option label="随心所写" value="3"/>
                <el-option label="剑指Offer" value="4"/>
              </el-select>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <MdEditor
                  v-model="article.content"
                  @onUploadImg="onUploadImg"
                  toolbarsExclude="['save']"
                  style="text-align: left"/>
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" @click="submitForm">确认修改</el-button>
            </el-form-item>
          </el-form>

        </template>
      </el-drawer>
    </el-main>
    <el-aside width="10%">

    </el-aside>
  </el-container>

</template>

<script setup>
import {MdEditor} from "md-editor-v3"
import 'md-editor-v3/lib/style.css'
import {ref} from "vue"
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
import {
  userallArticleService,
  articleDeleteService,
  articleDetailService,
  articleUpdateService,
  articleAddService
} from '/src/api/Article.js'
import axios from 'axios';
import {ElMessage, ElMessageBox} from "element-plus";
import {useTokenStore} from "../../stores/token.js";
import {favoriteDeleteService} from "../../api/Favorite.js";


//获取token
const tokenStore = useTokenStore();

const DialogVisible = ref(false)

const articlelist = ref([])

//控制抽屉
const drawer = ref(false)

//加载数据等待遮罩
const loading = ref(true)

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
            `

const article = ref({
  id:null,
  userid:null,
  title:"",
  coverurl:"",
  abstracts:"",
  content:"",
  category:null,
  createtime:"",
  updatetime:"",
  status:0,
  message:"",
  likenumber:0
})

//文章修改表单
const formRef = ref(null);

//定义表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 16, message: '长度为2~16位非空字符', trigger: 'blur' }
  ],
  abstract: [
    { required: true, message: '请输入文章概述', trigger: 'blur' },
    { min: 5, max: 50, message: '长度为5~50位非空字符', trigger: 'blur' }
  ],
  category:[
    {required:true,message:'请选择分类',trigger:'change'},
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    // { min: 5, max: 50, message: '长度为5~50位非空字符', trigger: 'blur' }
  ]
}

// 修改文章表单提交
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 通过验证，执行提交操作
      // ElMessage.success('验证成功')
      // 在这里发出请求
      ElMessageBox.confirm(
          '您确认要提交吗?',
          '温馨提示',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
      )
          .then(async () => {
            //1.
            // 修改文章内容
            editArticle()
          })
          .catch(() => {
            ElMessage.error('取消发布!')
          })
    } else {
      ElMessage.error("验证失败")
      return false;

    }
  });
};

//日期格式转换
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

//获取文章
const getArticleList = async () => {

  let result = await userallArticleService()
  articlelist.value = result.data

  loading.value = false

}
getArticleList()

//删除文章
const deleteArticle = (index,id) => {

  ElMessageBox.confirm(
      '您确定要删除这个文章吗?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {

        let result = await articleDeleteService(id)

        articlelist.value.splice(index,1)

        ElMessage.success("删除成功!")
      })
      .catch(() => {
        ElMessage.warning('取消删除!')
      })

}

//编辑文章
const editArticle = async () => {

  let result = await articleUpdateService(article)

  ElMessage.success("更新成功!")

  drawer.value = false

  getArticleList()

}

//获取文章
const getArticle = async (id) => {

  let result = await articleDetailService(id)
  // ElMessage.success()
  article.value = result.data

  drawer.value = true

}


// markdown编辑器中图片上传函数
const onUploadImg = async (files, callback) => {
  try {
    const res = await Promise.all(
        files.map((file) => {
          const form = new FormData();
          form.append('file', file);
          const isLt5M = files.size / 1024 / 1024 > 5;
          if(isLt5M){
            ElMessage.error("图片大小不能超过5M!")
            return ;
          }

          return axios.post('/api/upload', form, {
            headers: {
              'Authorization': tokenStore.token,
              'Content-Type': 'multipart/form-data'
            }
          });
        })
    );


    let url = res.map((item) => item.data.data);
    // 将图片URL以Markdown图片语法插入到编辑器内容中
    article.value.content += "![Image]("+url+")";

    //以下代码为测试res返回内容
    // console.log(res)
    // callback(res.map((item) => item.data));
    //console.log(url)

    // 将图片URL以Markdown图片语法插入到编辑器内容中
    // url.forEach(url => {
    //   article.value.content += "![Image]("+url.data+")";
    // });

  } catch (error) {
    ElMessage.error("上传失败!")
    console.error("Image upload failed: ", error);
  }
};


</script>

<style scoped>
.card-header{
  display: flex;
  justify-content: center;
  align-items: center;
}

</style>